<template>
  <xr-create
    :loading="loading"
    :title="title"
    :confirm-button-text="sureBtnTitle"
    @close="close"
    @save="saveClick"
  >
    <create-sections title="基本信息">
      <wk-form
        ref="crmForm"
        :model="fieldForm"
        :rules="fieldRules"
        :field-from="fieldForm"
        :field-list="fieldList"
        label-position="top"
        @change="formChange"
      >
        <template slot-scope="{ data }">
          <!-- <el-input
            v-if="data && data.field == 'threePartOrderNo'"
            v-model="data.threePartOrderNo"
            :maxlength="100"
            :placeholder="data.placeholder"
            @change="inputChange(data,$event)"
          /> -->
          <!-- {{fieldForm[data.field]}} -->
          <crm-relative-cell
            v-if="data && data.formType == 'customer'"
            :value="fieldForm[data.field]"
            :disabled="true"
            relative-type="customer"
            @value-change="otherChange($event, data)"
          />
          <crm-relative-cell
            v-if="data && data.formType == 'contract'"
            :value="fieldForm[data.field]"
            :disabled="true"
            :relation="data.relation"
            :relative-type="data.formType"
            @value-change="otherChange($event, data)"
          />
        </template>
      </wk-form>
    </create-sections>
    <el-button
      slot="footer"
      type="primary"
      plain
      @click.native="debouncedSaveField(true)"
      >保存草稿</el-button
    >
  </xr-create>
</template>

<script>
import { filedGetFieldAPI } from "@/api/crm/common";
import { crmOverdueSaveAPI, crmOverdueFindAPI } from "@/api/crm/overdue";

import XrCreate from "@/components/XrCreate";
import CreateSections from "@/components/CreateSections";
import WkForm from "@/components/NewCom/WkForm";
import { XhReceivablesPlan, CrmRelativeCell } from "@/components/CreateCom";
import WkApprovalFlowApply from "@/components/Examine/WkApprovalFlowApply";
import WkApprovalFlowApplyMixin from "@/components/Examine/mixins/WkApprovalFlowApply";
import crmTypeModel from "@/views/crm/model/crmTypeModel";
import CustomFieldsMixin from "@/mixins/CustomFields";
import { debounce } from "throttle-debounce";
import { objDeepCopy } from "@/utils";

export default {
  // 新建编辑
  name: "OverdueCreate",
  components: {
    XrCreate,
    CreateSections,
    CrmRelativeCell,
    XhReceivablesPlan,
    WkApprovalFlowApply,
    WkForm,
  },

  mixins: [CustomFieldsMixin, WkApprovalFlowApplyMixin],

  props: {
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {},
        };
      },
    },
  },

  data() {
    return {
      loading: false,
      baseFields: [],
      fieldList: [],
      fieldForm: {},
      fieldRules: {},
    };
  },

  computed: {
    title() {
      return this.action.type === "update" ? "编辑逾期" : "新建逾期";
    },

    editId() {
      return this.action.type == "update" ? this.action.id : "";
    },

    // 确认名称
    sureBtnTitle() {
      return "保存";
    },
  },

  watch: {},

  created() {
    this.debouncedSaveField = debounce(300, this.saveClick);

    this.getField();
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * 获取数据
     */

    getField() {
      console.log('获取数据')
      this.loading = true;
      const params = {
        label: crmTypeModel.overdue,
      };
      if (this.action.type == "update") {
        params.id = this.action.id;
      }
      filedGetFieldAPI(params)
        .then((res) => {
          const list = res.data || [];
          const fieldList = [];
          const fieldRules = {};
          const fieldForm = {};
          list.forEach((item) => {
            const temp = {};
            temp.field = item.fieldName;
            temp.formType = item.formType;
            temp.fieldId = item.fieldId;
            temp.inputTips = item.inputTips;
            temp.name = item.name;
            temp.setting = item.setting;

            const canEdit = this.getItemIsCanEdit(item, this.action.type);
            // 获取默认值
            fieldForm[temp.field] = this.getItemValue(
              item,
              this.action.data,
              this.action.type
            );
            // if(temp.field == "mobile"){
            // if(temp.field == "mobile"){
            //   temp.disabled = true;
            // }
            fieldRules[temp.field] = this.getRules(item);
            fieldList.push(temp);
          });

          this.baseFields = list;
          this.fieldList = fieldList;
          this.fieldForm = fieldForm;
          this.fieldRules = fieldRules;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    async getDefault(val){
      let params = {
        threePartOrderNo: val
      }
      const res = await crmOverdueFindAPI(params);
      if(res && res.data){
        let m = res.data;
        let contract= {
          contractId:m.contractId,
          contractNum:m.contractNum
        }
        let customer= {
          customerId:m.customerId,
          customerName:m.customerName
        }
        this.fieldForm.contractId = [contract];
        this.fieldForm.customerId = [customer];
        // this.fieldForm.mobile = m.mobile;
      }
    },
    /**
     * 保存
     */
    saveClick(isDraft = false) {
      this.loading = true;
      const crmForm = this.$refs.crmForm.instance;
      crmForm.validate((valid) => {
        if (valid) {
            const params = this.getSubmiteParams(
              this.baseFields,
              this.fieldForm
            );
            if (isDraft) {
              params.entity.checkStatus = 5;
            }
            this.submiteParams(params);
        } else {
          this.loading = false;
          // 提示第一个error
          this.getFormErrorMessage(crmForm);
          return false;
        }
      });
    },

    /**
     * 提交上传
     */
    submiteParams(params) {
      if (this.action.type == "update") {
        params.entity.overdueId = this.action.id;
        params.entity.batchId = this.action.batchId;
      }
      // 相关添加时候的多余提交信息
      if (
        this.action.relativeData &&
        Object.keys(this.action.relativeData).length
      ) {
        params = { ...params, ...this.action.relativeData };
      }

      crmOverdueSaveAPI(params)
        .then((res) => {
          this.loading = false;

          this.$message.success(
            this.action.type == "update" ? "编辑成功" : "添加成功"
          );
          this.close();
          // 保存成功
          this.$emit("save-success", {
            type: "overdue",
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 验证唯一
     */
    UniquePromise({ field, value }) {
      return this.getUniquePromise(field, value, this.action);
    },

    /**
     * change
     */
    inputChange(data,index,value) {
      this.getDefault(value)
    },
    formChange(field, index, value, valueList) {
      if(field.field == 'threePartOrderNo'){
        this.getDefault(value)
      }
    },
    close() {
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped>
.wk-form {
  /deep/ .el-form-item.is-product {
    flex: 0 0 100%;
    width: 0;
  }
}
</style>
